﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MotorLibrary.Service
{
    public class DescargadorHttp: IDescargador
    {
        private string ConfigurarArchivo(string extension)
        {
            string resultado;

            if (extension == ".pdf")
            {
                resultado = "Application/pdf";
            }
            else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
            {
                resultado = "image";
            }
            else if (extension == ".json")
            {
                resultado = "text/plain";
            }
            else
            {
                throw new NotImplementedException("Extensión de archivo no permitida.");
            }

            return resultado;
        }

        public long Descarga(string origen, string destino)
        {
            string extension = Path.GetExtension(origen);
            string configurar = ConfigurarArchivo(extension);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(origen);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Check that the remote file was found. The ContentType
            // check is performed since a request for a non-existent
            // image file might be redirected to a 404-page, which would
            // yield the StatusCode "OK", even though the image was not
            // found.
            if ((response.StatusCode == HttpStatusCode.OK ||
                response.StatusCode == HttpStatusCode.Moved ||
                response.StatusCode == HttpStatusCode.Redirect) &&
                response.ContentType.StartsWith(configurar, StringComparison.OrdinalIgnoreCase))
            {
                // if the remote file was found, download it
                int total = 0;
                using (Stream inputStream = response.GetResponseStream())
                using (Stream outputStream = File.OpenWrite(destino))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    do
                    {
                        bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                        total += bytesRead;
                        outputStream.Write(buffer, 0, bytesRead);
                    } while (bytesRead != 0);
                }
                return total;
            }
            else
            {
                throw new FileNotFoundException();
            }
        }
    }
}
